<script setup lang="ts">
import { toast } from 'sard-uniapp'
import { t } from '@/locale'
import { useLoginHandler } from '../composable/useLogin'

interface Props {
  agreeTerms: boolean
  redirectUrl?: string
}

interface Emits {
  (e: 'update:agreeTerms', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const { doWechatLogin } = useLoginHandler()

async function handleWechatLogin() {
  if (!props.agreeTerms) {
    toast.fail(t('login.please_agree_terms'))
    return
  }

  await doWechatLogin(props.redirectUrl)
}

function handleAgreeTermsChange(value: boolean) {
  emit('update:agreeTerms', value)
}
</script>

<template>
  <view class="wechat-login">
    <!-- #ifdef MP-WEIXIN -->
    <view class="flex flex-col items-center space-y-6">
      <sar-button
        type="pale"
        theme="success"
        size="large"
        root-style="width: 600rpx; border-radius:16px"
        @click="handleWechatLogin"
      >
        {{ $t('login.wechat_one_click_login') }}
      </sar-button>

      <view class="flex items-center space-x-2">
        <sar-checkbox
          :model-value="props.agreeTerms"
          @change="handleAgreeTermsChange"
        />
        <text class="text-sm text-gray-600">
          {{ $t('login.agree_terms') }}
          <text class="text-blue-500">{{ $t('login.user_agreement') }}</text>
          {{ $t('login.and') }}
          <text class="text-blue-500">{{ $t('login.privacy_policy') }}</text>
        </text>
      </view>
    </view>
    <!-- #endif -->

    <!-- #ifndef MP-WEIXIN -->
    <view class="py-8 text-center text-gray-500">
      <text>{{ $t('login.wechat_only_in_mp') }}</text>
    </view>
    <!-- #endif -->
  </view>
</template>

<style scoped>
.wechat-login {
  padding: 0;
}
</style>
